<template>
  <div class="channel-edit">
    <van-cell center :border="false">
      <div slot="title" class="channel-title">我的频道</div>
      <van-button
        size="mini"
        round
        type="danger"
        plain
        @click="isEdit = !isEdit"
        >{{ isEdit ? '完成' : '编辑' }}</van-button
      >
    </van-cell>
    <van-grid :gutter="10">
      <van-grid-item
        class="grid-item"
        :class="{ active: index === active }"
        :icon="isEdit && index !== 0 ? 'clear' : ''"
        v-for="(channel, index) in userChannels"
        :key="index"
        :text="channel.name"
        @click="onUserChannelClick(channel, index)"
      />
    </van-grid>
    <van-cell title="频道推荐" :border="false"></van-cell>
    <van-grid :gutter="10">
      <van-grid-item
        class="grid-item"
        v-for="(channel, index) in recommendChannels"
        :key="index"
        :text="channel.name"
        @click="onAdd(channel)"
      />
    </van-grid>
  </div>
</template>

<script>
import {
  getAllChannels,
  addUserChannel,
  deleteUserChannel,
} from '@/api/channel'
import { mapState } from 'vuex'
import { setItem } from '@/utils/storage'
export default {
  name: 'ChannelEdit',
  components: {},
  props: {
    //   不能带符号，只能转成驼峰
    userChannels: {
      type: Array,
      required: true,
    },
    active: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      allChannels: [],
      isEdit: false,
    }
  },
  computed: {
    ...mapState(['user']),

    recommendChannels() {
      return this.allChannels.filter((channel) => {
        // 判断channel是否属于用户频道
        return !this.userChannels.find((userChannel) => {
          // 找到满足该条件的元素
          return userChannel.id === channel.id
        })
      })
    },
  },
  watch: {},
  created() {
    this.loadAllChannels()
  },
  mounted() {},
  methods: {
    async loadAllChannels() {
      const { data } = await getAllChannels()
      this.allChannels = data.data.channels
    },
    async onAdd(channel) {
      // 已登录，将数据存储到线上
      try {
        if (this.user) {
          await addUserChannel({
            id: channel.id,
            seq: this.userChannels.length,
          })
        } else {
          // 未登录，将数据存储到本地
          setItem('channels', [...this.userChannels, channel])
        }

        // 更新视图
        this.userChannels.push(channel)
      } catch (err) {
        console.log(err)
        this.$toast('添加失败,请稍后重试')
      }
    },
    onUserChannelClick(index) {
      if (this.isEdit && index !== 0) {
        // 编辑状态，删除频道
        this.deleteChannel(index)
      } else {
        // 非编辑状态，切换频道
        this.switchChannel(index)
      }
    },
    async deleteChannel(channel, index) {
      try {
        if (this.user) {
          // 已登录，删除线上数据
          await deleteUserChannel(channel.id)
          this.userChannels.splice(index, 1)
        } else {
          // 未登录，删除本地数据
          this.userChannels.splice(index, 1)
          setItem('channels', this.userChannels)
        }
        // 如果删除的是当前激活频道前面的频道，则更新激活频道
        if (index <= this.value) {
          this.$emit('input', this.value - 1)
        }
      } catch (err) {
        console.log(err)
        this.$toast('操作失败，请稍后重试')
      }
    },
    switchChannel(index) {
      // 切换频道
      this.$emit('update-active', index)
      // 关闭弹出层
      this.$emit('close')
    },
  },
}
</script>

<style scoped lang="less">
.channel-edit {
  padding-top: 54px;

  .channel-title {
    font-size: 16px;
    color: #333;
  }

  .gird-item {
    width: 80px;
    height: 43px;
  }
  /deep/.van-grid-item__text {
    color: #222;
    font-size: 14px;
    margin-top: 0;
  }
  /deep/.van-grid-item__content {
    background-color: #f4f5f6;
  }
  /deep/ .van-grid-item__icon {
    position: absolute;
    right: -5px;
    top: -5px;
    font-size: 20px;
    color: #ccc;
  }
  .active {
    /deep/.van-grid-item__text {
      color: blue !important;
    }
  }
}
</style>
